//
//  KeyboardViewController.m
//  coolkeys.extention
//
//  Created by yww on 31/07/2017.
//  Copyright © 2017 yww. All rights reserved.
//

#import "KeyboardViewController.h"
#import "keyBtn.h"
#import <AudioToolbox/AudioToolbox.h>
#import <Speech/Speech.h>
#import "IFlyMSC/IFlyMSC.h"
#import "Definition.h"
#import <QuartzCore/QuartzCore.h>
#import "ISRDataHelper.h"
#import "PopupView.h"
#import "IATConfig.h"

@interface KeyboardViewController ()<IFlySpeechRecognizerDelegate,IFlyRecognizerViewDelegate>

@property (nonatomic, strong) UIButton *nextKeyboardButton;
@property (nonatomic, strong) UIView   *backView;
@property (nonatomic, strong) NSArray  *capitalWords;
@property (nonatomic, strong) NSArray  *lowercaseWords;
@property (nonatomic, strong) NSArray  *animationImages;
@property (nonatomic, strong) NSArray  *clickAnimationImages;
@property (nonatomic, strong) NSArray  *symbols;
@property (nonatomic, strong) NSArray  *numbers;
@property (nonatomic, strong) UIImageView  *clickAnimationImageView;
@property (nonatomic, strong) UIImageView  *voiceImageView;
@property (nonatomic, strong) UILabel  *voiceTipLabel;
@property (nonatomic, strong) UIButton *backKeyboardBtn;

@property (nonatomic, assign) BOOL isCapital;
@property (nonatomic, assign) BOOL isNumber;
@property (nonatomic, assign) BOOL isSymbol;
@property (nonatomic, assign) BOOL isVoiceSpeech;
@property (nonatomic, strong) UIButton *returnBtn;
@property (nonatomic, strong) UIButton *spaceBtn;
@property (nonatomic, strong) UIButton *voiceBtn;
@property (nonatomic, strong) UIButton *numberSwitchBtn;
@property (nonatomic, strong) UIButton *caseBtn;
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) NSTimer  *timer;
@property (nonatomic, assign) CGFloat   time;
@property (nonatomic, assign) BOOL      isIpad;
@property (nonatomic, assign) CGFloat   iPadHeight;
@property (nonatomic, assign) CGFloat   iPhoneHeight;

//讯飞
@property (nonatomic, strong) IFlySpeechRecognizer *iFlySpeechRecognizer;//Recognition conrol without view
@property (nonatomic, strong) IFlyRecognizerView *iflyRecognizerView;//Recognition control with view
@property (nonatomic, strong) PopupView *popUpView;
@property (nonatomic, assign) BOOL isCanceled;
@property (nonatomic,assign) BOOL isBeginOfSpeech;//Whether or not SDK has invoke the delegate methods of beginOfSpeech.

//语音识别 自带
//@property (strong, nonatomic) SFSpeechRecognitionTask *recognitionTask; //语音识别任务
//@property (strong, nonatomic)SFSpeechRecognizer *speechRecognizer; //语音识别器
//@property (strong, nonatomic) SFSpeechAudioBufferRecognitionRequest *recognitionRequest; //识别请求
//@property (strong, nonatomic)AVAudioEngine *audioEngine; //录音引擎
@end

@implementation KeyboardViewController
#pragma  mark 懒加载
- (NSTimer *)timer{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                         target: self
                                       selector: @selector(handleTimer:)
                                       userInfo: nil
                                        repeats: YES];
    }
    return _timer;
}
- (UIImageView *)voiceImageView{
    if (!_voiceImageView) {
        // 读取gif图片数据
        UIImageView *voiceImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)];
        voiceImageView.center = self.inputView.center;
        NSMutableArray *imagesArr = [NSMutableArray array];
        for (int i = 0;i <14;i ++) {
            UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"sound_wave-%d",i+1]];
            if (image) {
                [imagesArr addObject:image];
            }
        }
        voiceImageView.animationImages = imagesArr; //获取Gif图片列表
        voiceImageView.animationDuration = 2.0;     //执行一次完整动画所需的时长
        voiceImageView.animationRepeatCount = 0;  //动画重复次数
        [voiceImageView startAnimating];
        _voiceImageView = voiceImageView;
    }
    return _voiceImageView;
}



- (UIButton *)returnBtn{
    if (!_returnBtn) {
         CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *createReturnBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.75*KdeviceWidth, 3*(heigt +6)+5,0.25*KdeviceWidth-2, heigt)];
        [createReturnBtn setTitle:@"Return" forState:UIControlStateNormal];
        createReturnBtn.backgroundColor = [UIColor lightGrayColor];
        [createReturnBtn addTarget:self action:@selector(retrnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        createReturnBtn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
        createReturnBtn.layer.cornerRadius = 5;
        createReturnBtn.clipsToBounds = YES;
        _returnBtn = createReturnBtn;
    }
    return _returnBtn;
}
- (UIButton *)backKeyboardBtn{
    if (!_backKeyboardBtn) {
        CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *backKeyboardBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.75*KdeviceWidth, 3*(heigt +6)+5,50, heigt)];
        [backKeyboardBtn setTitle:@"Return" forState:UIControlStateNormal];
        [backKeyboardBtn setImage:[UIImage imageNamed:@"keyboard"] forState:UIControlStateNormal];
        backKeyboardBtn.backgroundColor = [UIColor clearColor];
        [backKeyboardBtn addTarget:self action:@selector(backKeyboardBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        backKeyboardBtn.layer.cornerRadius = 5;
        backKeyboardBtn.clipsToBounds = YES;
        _backKeyboardBtn = backKeyboardBtn;
    }
    return _backKeyboardBtn;
}
- (UILabel *)voiceTipLabel{
    if (!_voiceTipLabel) {
        CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        _voiceTipLabel = [[UILabel alloc]initWithFrame:CGRectMake((KdeviceWidth-100)/2.0, 3*(heigt +6)+25, 100, 20)];
        _voiceTipLabel.text = @"[Speech]";
        _voiceTipLabel.backgroundColor = [UIColor clearColor];
        _voiceTipLabel.textAlignment = NSTextAlignmentCenter;
        _voiceTipLabel.font = [UIFont boldSystemFontOfSize:16];
        _voiceTipLabel.textColor = [UIColor blackColor];
    }
    return _voiceTipLabel;
}
- (UIButton *)voiceBtn{
    if (!_voiceBtn) {
        CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *voiceBtn = [[UIButton alloc]initWithFrame:CGRectMake(110, 3*(heigt +6)+5, 3.0*heigt/4, heigt)];
        [voiceBtn setImage:[UIImage imageNamed:@"speech"] forState:UIControlStateNormal];
        voiceBtn.backgroundColor = [UIColor lightGrayColor];
        [voiceBtn addTarget:self action:@selector(voiceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        voiceBtn.layer.cornerRadius = 5;
        voiceBtn.clipsToBounds = YES;
        _voiceBtn = voiceBtn;
    }
    return _voiceBtn;
}
- (UIButton *)spaceBtn{
    if (!_spaceBtn) {
         CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *spaceBtn = [[UIButton alloc]initWithFrame:CGRectMake(115+3.0*heigt/4, 3*(heigt +6)+5, 0.75*KdeviceWidth-120-3.0*heigt/4, heigt)];
        [spaceBtn setTitle:@"space" forState:UIControlStateNormal];
        spaceBtn.backgroundColor = [UIColor lightGrayColor];
        [spaceBtn addTarget:self action:@selector(spaceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        spaceBtn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
        spaceBtn.layer.cornerRadius = 5;
        spaceBtn.clipsToBounds = YES;
        _spaceBtn = spaceBtn;
    }
    return _spaceBtn;
}
- (UIButton *)numberSwitchBtn{
    if (!_numberSwitchBtn) {
         CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *numberSwitchBtn = [[UIButton alloc]initWithFrame:CGRectMake(2, 3*(heigt +6)+5, 50, heigt)];
        [numberSwitchBtn setTitle:@"123" forState:UIControlStateNormal];
        numberSwitchBtn.backgroundColor = [UIColor lightGrayColor];
        [numberSwitchBtn addTarget:self action:@selector(numberSwitchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        numberSwitchBtn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
        numberSwitchBtn.layer.cornerRadius = 5;
        numberSwitchBtn.clipsToBounds = YES;
        _numberSwitchBtn = numberSwitchBtn;
    }
    return _numberSwitchBtn;
}
- (UIButton *)caseBtn{
    if (!_caseBtn) {
        CGFloat W = 0.3*KdeviceWidth /2.0;
        CGFloat width = W>50?50:W;
        CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        UIButton *caseBtn = [[UIButton alloc]initWithFrame:CGRectMake(2, 2*(heigt+6)+5, width, heigt)];
        [caseBtn setImage:[UIImage imageNamed:@"uperCase_down"] forState:UIControlStateNormal];
        caseBtn.backgroundColor = [UIColor clearColor];
        [caseBtn addTarget:self action:@selector(caseBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        caseBtn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
        caseBtn.layer.cornerRadius = 5;
        caseBtn.clipsToBounds = YES;
        caseBtn.adjustsImageWhenHighlighted = NO;
        _caseBtn = caseBtn;
    }
    return _caseBtn;
}
- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        CGFloat W = 0.3*KdeviceWidth /2.0;
        CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
        CGFloat width = W>50?50:W;
        UIButton *deleteBtn = [[UIButton alloc]initWithFrame:CGRectMake(KdeviceWidth-width-2, 2*(heigt +6)+5, width, heigt)];
        deleteBtn.backgroundColor = [UIColor clearColor];
        [deleteBtn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        deleteBtn.layer.cornerRadius = 5;
        deleteBtn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
        deleteBtn.clipsToBounds = YES;
        [deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        _deleteBtn = deleteBtn;
    }
    return _deleteBtn;
}
- (UIView *)backView{
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.inputView.frame.size.width, self.inputView.frame.size.height)];
        _backView.userInteractionEnabled = YES;
        _backView.backgroundColor = [UIColor redColor];
    }
    return _backView;
}
- (NSArray *)lowercaseWords{
    if (!_lowercaseWords) {
        _lowercaseWords = @[@"q",@"w",@"e",@"r",@"t",@"y",@"u",@"i",@"o",@"p",@"a",@"s",@"d",@"f",@"g",@"h",@"j",@"k",@"l",@"z",@"x",@"c",@"v",@"b",@"n",@"m"];
    }
    return _lowercaseWords;
}
- (NSArray *)capitalWords{
    if (!_capitalWords) {
        _capitalWords = @[@"Q",@"W",@"E",@"R",@"T",@"Y",@"U",@"I",@"O",@"P",@"A",@"S",@"D",@"F",@"G",@"H",@"J",@"K",@"L",@"Z",@"X",@"C",@"V",@"B",@"N",@"M"];
    }
    return _capitalWords;
}
- (NSArray *)symbols{
    if (!_symbols) {
        _symbols = @[@"[",@"]",@"{",@"}",@"#",@"%",@"^",@"*",@"+",@"=",@"_",@"\\",@"/",@"~",@"<",@">",@"€",@"￡",@"¥",@"·",@".",@",",@"?",@"!",@"'"];
    }
    return _symbols;
}
- (NSArray *)numbers{
    if (!_numbers) {
        _numbers = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",@"-",@"/",@":",@";",@"(",@")",@"$",@"&",@"@",@"\"",@".",@",",@"?",@"!",@"'"];
    }
    return _numbers;
}
- (NSArray *)animationImages{
    if (!_animationImages) {
        NSMutableArray *imagesArr = [NSMutableArray array];
        for (int i = 0;i <14;i ++) {
            UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:@"skull-%d",i+1]];
            if (image) {
                [imagesArr addObject:image];
            }
        }
        _animationImages = imagesArr;
    }
    return _animationImages;
}
- (NSArray *)clickAnimationImages{
    if (!_clickAnimationImages) {
        NSMutableArray *imagesArr = [NSMutableArray array];
        for (int i = 0;i <49;i ++) {
            NSString *imagname = [NSString stringWithFormat:@"bomb-%d",i+1];
            UIImage *image = [UIImage imageNamed: imagname];
            if (image) {
                [imagesArr addObject:image];
            }
        }
        _clickAnimationImages = imagesArr;
    }
    return _clickAnimationImages;
}
#pragma  mark 初始化
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    //语音识别初始化
    [self initRecognizer];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect rect = [UIScreen mainScreen].bounds;
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad){
        self.isIpad = YES;
        self.iPadHeight = rect.size.height / 18.6;
    }else{
        self.isIpad = NO;
        self.iPhoneHeight = rect.size.height / 14.7;
    }
    //添加背景
    //    [self.view addSubview:self.backView];
    
    //添加切换键
    [self crateNextView];
    
    //添加按键
    [self createKeyView];
 
    //配置讯飞语音识别
    [self localSpeechSetting];
    
}
 
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
    if ([IATConfig sharedInstance].haveView == NO) {
        
        [_iFlySpeechRecognizer cancel];
        [_iFlySpeechRecognizer setDelegate:nil];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        
    }
    else
    {
        [_iflyRecognizerView cancel];
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated
}
#pragma  mark 方法
- (void)crateNextView{
    self.nextKeyboardButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextKeyboardButton.backgroundColor = [UIColor lightGrayColor];
    self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = NO;
    [self.nextKeyboardButton setImage:[[UIImage imageNamed:@"globalNet"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    CGFloat heigt = self.isIpad?self.iPadHeight:self.iPhoneHeight;
    self.nextKeyboardButton.frame = CGRectMake(55, 3*(heigt +6)+5, 50, heigt);
    [self.nextKeyboardButton addTarget:self action:@selector(handleInputModeListFromView:withEvent:) forControlEvents:UIControlEventAllTouchEvents];
    self.nextKeyboardButton.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
    self.nextKeyboardButton.layer.cornerRadius = 5;
    self.nextKeyboardButton.clipsToBounds = YES;
    [self.inputView addSubview:self.nextKeyboardButton];
}
- (void)createKeyView{
    if (!self.isNumber && !self.isSymbol) {
        //第一排
        for (int i = 0; i < 10; i++) {
            [self addBtnWithIndex:i tag:i row:0 magin:2];
        }
        //第二排
        for (int i = 10; i < 19; i++) {
            [self addBtnWithIndex:(i-10) tag:i row:1 magin:KdeviceWidth/20];
        }
        //第三排
        for (int i = 19; i < 26; i++) {
            [self addBtnWithIndex:(i-19) tag:i row:2 magin:3*KdeviceWidth/20];
        }
        
        //大小写切换键 符号数字切换键
        [self.inputView addSubview:self.caseBtn];
        //        if (self.isCapital) {
        //            [self.caseBtn setImage:[UIImage imageNamed:@"uperCase_up"] forState:UIControlStateNormal];
        //        }else{
        //            [self.caseBtn setImage:[UIImage imageNamed:@"uperCase_down"] forState:UIControlStateNormal];
        //        }
        
        //删除键
        [self.inputView addSubview:self.deleteBtn];
        [self addLongDelete];
        //数字 字母切换
        [self.inputView addSubview:self.numberSwitchBtn];
        //语音
        [self.inputView addSubview:self.voiceBtn];
        //空格
        [self.inputView addSubview:self.spaceBtn];
        //return
        [self.inputView addSubview:self.returnBtn];
        //方框
        self.inputView.layer.borderWidth = 1.0;
        self.inputView.layer.borderColor = [UIColor grayColor].CGColor;
    }
}
- (void)addBtnWithIndex:(NSInteger)index tag:(NSInteger)tag row:(NSInteger)row magin:(NSInteger)magin{
    
    CGFloat height = self.isIpad?self.iPadHeight:self.iPhoneHeight;
    CGFloat width;
    if (row == 2) {
        width = self.isNumber?(7*KdeviceWidth/50 -4):(KdeviceWidth/10 -4);
    }else{
        width = (KdeviceWidth/10 -4);
    }
    
    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(magin+ index*(width+4),row*(height +6)+5, width,height)];
    gifImageView.layer.cornerRadius = 5;
    gifImageView.userInteractionEnabled = YES;
    gifImageView.clipsToBounds = YES;
    gifImageView.animationImages = self.animationImages; //获取Gif图片列表
    gifImageView.animationDuration = 1;     //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 0;  //动画重复次数
    [gifImageView startAnimating];
    [self.inputView addSubview:gifImageView];
    
    
    keyBtn *btn = [[keyBtn alloc]initWithFrame:CGRectMake(magin+ index*(width+4),row*(height +6)+5,width, height)];
    //  btn.backgroundColor = [UIColor clearColor];
    
    btn.tag = tag;
    btn.layer.cornerRadius = 5;
    btn.clipsToBounds = YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:self.isIpad?25:20];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    if (!self.isNumber && !self.isSymbol ) {
        [btn setTitle:self.isCapital?self.capitalWords[tag]:self.lowercaseWords[tag] forState:UIControlStateNormal];
    }else if (self.isNumber){
        [btn setTitle: self.numbers[tag] forState:UIControlStateNormal];
    }
    
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.inputView addSubview:btn];
}
- (void)addBtnAudio{
    // 比如添加一个：截图音效
    SystemSoundID audioURLSound;
    // 1. 定义要播放的音频文件的URL
    NSURL *audioURL = [[NSBundle mainBundle] URLForResource:@"yinxiao2" withExtension:@"wav"];
    // 2. 注册音频文件（第一个参数是音频文件的URL 第二个参数是音频文件的SystemSoundID）
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioURL,&audioURLSound);
    // 3. 为crash播放完成绑定回调函数、可不绑定
    // AudioServicesAddSystemSoundCompletion(screenshot, NULL, NULL, (void*)completionCallback, NULL);
    // 4. 播放 ditaVoice 注册的音频 并控制手机震动
    AudioServicesPlaySystemSound(audioURLSound); // 只播放声音
    // AudioServicesPlayAlertSound(screenshotSound); // 同时手机会震动
    // AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); // 控制手机振动
}
- (void)addLongDelete{
    [self.deleteBtn addTarget:self action:@selector(offsetButtonTouchBegin:)forControlEvents:UIControlEventTouchDown];
    [self.deleteBtn addTarget:self action:@selector(offsetButtonTouchEnd:)forControlEvents:UIControlEventTouchUpInside];
    [self.deleteBtn addTarget:self action:@selector(offsetButtonTouchEnd:)forControlEvents:UIControlEventTouchUpOutside];
}
#pragma  mark  按钮 监听 通知 手势

-(void) offsetButtonTouchBegin:(id)sender{
    NSLog(@"开始计时");
    self.time = 0.0;
    [self.timer setFireDate:[NSDate distantPast]];
}

-(void) offsetButtonTouchEnd:(id)sender{
    NSLog(@"计时结束");
    [self.timer setFireDate:[NSDate distantFuture]];
}

-(void) handleTimer:(id)sender{
     self.time = self.time + 0.1;
    if (self.time >0.8) {
        [self.textDocumentProxy deleteBackward];
    }
}
- (void)caseBtnClick:(UIButton *)btn{
    if (!self.isNumber) {
        self.isCapital = !self.isCapital;
        if (self.isCapital) {
            [btn setImage:[UIImage imageNamed:@"uperCase_up"] forState:UIControlStateNormal];
        }else{
            [btn setImage:[UIImage imageNamed:@"uperCase_down"] forState:UIControlStateNormal];
        }
        for (UIView *view in self.inputView.subviews) {
            if ([view isKindOfClass:[keyBtn class]]) {
                keyBtn *btnn = (keyBtn*)view;
                [btnn setTitle:self.isCapital?self.capitalWords[btnn.tag]:self.lowercaseWords[btnn.tag] forState:UIControlStateNormal];
            }
        }

    }else{//符号
        self.isSymbol = !self.isSymbol;
        
        if (self.isSymbol) {
            [self.caseBtn setTitle:@"123" forState:UIControlStateNormal];
        }else{
            [self.caseBtn setTitle:@"#+-" forState:UIControlStateNormal];
        }
        for (UIView *view in self.inputView.subviews) {
            if ([view isKindOfClass:[keyBtn class]]) {
                keyBtn *btnn = (keyBtn*)view;
                [btnn setTitle:self.isSymbol?self.symbols[btnn.tag]:self.numbers[btnn.tag] forState:UIControlStateNormal];
            }
        }
        
    }
}

- (void)btnClick:(keyBtn *)btn{
    if (self.isSymbol){
        [self.textDocumentProxy insertText: self.symbols[btn.tag]];
    }else if (self.isNumber){
        [self.textDocumentProxy insertText: self.numbers[btn.tag]];
    }else  if (!self.isNumber && !self.isSymbol ) {
        [self.textDocumentProxy insertText:self.isCapital?self.capitalWords[btn.tag]:self.lowercaseWords[btn.tag]];
    }
 
    //添加声音
    [self addBtnAudio];
    
    //动图
   __block UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,btn.frame.size.width,btn.frame.size.height)];
    gifImageView.layer.cornerRadius = 5;
    gifImageView.tag = btn.tag;
    gifImageView.userInteractionEnabled = YES;
    gifImageView.clipsToBounds = YES;
    gifImageView.animationImages = self.clickAnimationImages; //获取Gif图片列表
    gifImageView.animationDuration = 0.4;     //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 0;  //动画重复次数
    [gifImageView startAnimating];
//    self.clickAnimationImageView = gifImageView;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [btn addSubview:gifImageView];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
        [gifImageView addGestureRecognizer:tapGesture];
        tapGesture.view.tag = gifImageView.tag;
        [btn bringSubviewToFront:gifImageView];
    });
     
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [gifImageView removeFromSuperview];
         gifImageView = nil;
    });
    
}

- (void)tapGesture:(UITapGestureRecognizer *)tap{
    UIView *tapView = (UIView*) tap.view;
    
    /*
     if ([tapView isKindOfClass:[UIImageView class]]) {
     UIImageView *imageView = (UIImageView *)tapView;
     [imageView stopAnimating];
     }
     [tapView removeFromSuperview];
     */
 
    NSUInteger tag = tapView.tag;
    if (self.isSymbol){
        [self.textDocumentProxy insertText: self.symbols[tag]];
    }else if (self.isNumber){
        [self.textDocumentProxy insertText: self.numbers[tag]];
    }else  if (!self.isNumber && !self.isSymbol ) {
        [self.textDocumentProxy insertText:self.isCapital?self.capitalWords[tag]:self.lowercaseWords[tag]];
    }
    [self addBtnAudio];
//    NSLog(@"点击 tag == %ld",tag);
}
- (void)deleteBtnClick:(UIButton *)btn{
    [self.textDocumentProxy deleteBackward];
}
- (void)spaceBtnClick:(UIButton *)btn{
    [self.textDocumentProxy insertText:@" "];
}
- (void)voiceBtnClick:(UIButton *)btn{
    NSLog(@"语音");
    for (UIView *view in self.inputView.subviews) {
        if ([view isKindOfClass:[keyBtn class]]) {
            keyBtn *btnn = (keyBtn*)view;
            btnn.hidden = YES;
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView*)view;
            imageView.hidden = YES;
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
    }
    self.isVoiceSpeech = YES;
    self.caseBtn.hidden = YES;
    self.numberSwitchBtn.hidden = YES;
    self.voiceBtn.hidden = YES;
    self.spaceBtn.hidden = YES;
    self.deleteBtn.hidden = YES;
    self.returnBtn.hidden = YES;
    self.nextKeyboardButton.backgroundColor = [UIColor clearColor];
    [self.inputView addSubview:self.voiceImageView];
    [self.inputView addSubview:self.backKeyboardBtn];
    [self.inputView addSubview:self.voiceTipLabel];
    //开始
    [self startSpeech];
//    [self startRecording ];
    
    
}

//返回键盘
- (void)backKeyboardBtnClick:(UIButton *)btn{
    self.isCanceled = YES;
    //停止语音
    [_iFlySpeechRecognizer stopListening];
    
    for (UIView *view in self.inputView.subviews) {
        if ([view isKindOfClass:[keyBtn class]]) {
            keyBtn *btnn = (keyBtn*)view;
            btnn.hidden = NO;
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView*)view;
            imageView.hidden = NO;
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
    }
    self.isVoiceSpeech = NO;
    self.caseBtn.hidden = NO;
    self.numberSwitchBtn.hidden = NO;
    self.voiceBtn.hidden = NO;
    self.spaceBtn.hidden = NO;
    self.deleteBtn.hidden = NO;
    self.returnBtn.hidden = NO;
    self.nextKeyboardButton.backgroundColor = [UIColor lightGrayColor];
    [self.voiceImageView removeFromSuperview];
    [self.backKeyboardBtn removeFromSuperview];
    [self.voiceTipLabel removeFromSuperview];
    
}
-(void)retrnBtnClick:(UIButton *)btn{
    [self.textDocumentProxy insertText:@"\n"];
    [self dismissKeyboard];
    
}
- (void)numberSwitchBtnClick:(UIButton *)btn{
    self.isNumber = !self.isNumber;
    self.isSymbol = NO;
    for (UIView *view in self.inputView.subviews) {
        if ([view isKindOfClass:[keyBtn class]]) {
            keyBtn *btnn = (keyBtn*)view;
            [btnn removeFromSuperview];
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
        if ([view isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView*)view;
            [imageView removeFromSuperview];
            //                [btnn setTitle: self.numbers[btnn.tag] forState:UIControlStateNormal];
        }
    }
    if (self.isNumber) {
        //第一排
        for (int i = 0; i < 10; i++) {
            [self addBtnWithIndex:i tag:i row:0 magin:2];
        }
        //第二排
        for (int i = 10; i < 20; i++) {
            [self addBtnWithIndex:(i-10) tag:i row:1 magin:2];
        }
        //第三排
        for (int i = 20; i < 25; i++) {
            [self addBtnWithIndex:(i-20) tag:i row:2 magin:3*KdeviceWidth/20];
        }
        [self.numberSwitchBtn setTitle:@"ABC" forState:UIControlStateNormal];
        [self.caseBtn setImage:nil forState:UIControlStateNormal];
        [self.caseBtn setTitle:@"#+-" forState:UIControlStateNormal];
        self.caseBtn.backgroundColor = [UIColor lightGrayColor];
    }else{
        //第一排
        for (int i = 0; i < 10; i++) {
            [self addBtnWithIndex:i tag:i row:0 magin:2];
        }
        //第二排
        for (int i = 10; i < 19; i++) {
            [self addBtnWithIndex:(i-10) tag:i row:1 magin:KdeviceWidth/20];
        }
        //第三排
        for (int i = 19; i < 26; i++) {
            [self addBtnWithIndex:(i-19) tag:i row:2 magin:3*KdeviceWidth/20];
        }
        [self.numberSwitchBtn setTitle:@"123" forState:UIControlStateNormal];
        [self.caseBtn setImage:[UIImage imageNamed:@"uperCase_down"] forState:UIControlStateNormal];
        [self.caseBtn setTitle:nil forState:UIControlStateNormal];
        self.caseBtn.backgroundColor = [UIColor clearColor];
    }
    
}

#pragma  mark 语音识别相关
//开始录音
- (void)startSpeech{
    if ([IATConfig sharedInstance].haveView == NO) {
        self.isCanceled = NO;
        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }
        
        //将麦克风设置为音频源
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置结果类型
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //在SDK的本地存储路径中生成保存的录制文件的音频名称，默认在library / cache中。
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        //设置代理
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {
             [_popUpView showText: @"plsease speech"];
            
        }else{
            [_popUpView showText: NSLocalizedString(@"M_ISR_Fail", nil)];
        }
    }else {
        
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
        //将麦克风设置为音频源
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //设置结果类型
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //在SDK的本地存储路径中生成保存的录制文件的音频名称，默认在library / cache中。
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        BOOL ret = [_iflyRecognizerView start];
        if (ret) {
            NSLog(@"开始");
        }
    }
}

- (void)localSpeechSetting{
    //    self.voiceBtn.enabled = false;
    
    //讯飞
    [IFlySetting setLogFile:LVL_ALL];
    [IFlySetting showLogcat:YES];
    
    //设置SDK的本地存储路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    
    //设置APPID
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@",APPID_VALUE];
    
    //配置和初始化iflytek服务
    [IFlySpeechUtility createUtility:initString];
    
    _popUpView = [[PopupView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) withParentView:self.view];
    _popUpView.center = self.view.center;
    
    
    
    //发送语音认证请求(首先要判断设备是否支持语音识别功能)
    [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        bool isButtonEnabled = false;
        switch (status) {
            case SFSpeechRecognizerAuthorizationStatusAuthorized:
                isButtonEnabled = true;
                NSLog(@"可以语音识别");
                break;
            case SFSpeechRecognizerAuthorizationStatusDenied:
                isButtonEnabled = false;
                NSLog(@"用户被拒绝访问语音识别");
                break;
            case SFSpeechRecognizerAuthorizationStatusRestricted:
                isButtonEnabled = false;
                NSLog(@"不能在该设备上进行语音识别");
                break;
            case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                isButtonEnabled = false;
                NSLog(@"没有授权语音识别");
                break;
            default:
                break;
        }
        
    }];
    
    
    //自带语音
    /*
     //设备识别语言为中文
     NSLocale *cale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh-CN"];
     self.speechRecognizer = [[SFSpeechRecognizer alloc]initWithLocale:cale];
     
     //设置代理
     _speechRecognizer.delegate = self;
     
     　　//创建录音引擎
     self.audioEngine = [[AVAudioEngine alloc]init];
     */
    
}
-(void)initRecognizer{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //无场景差别识别
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        }
        //添加硬件参数
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        //在启动录音器前设置AVAudioSession的Category属性 0表示不调用；1表示调用（默认）
        [_iFlySpeechRecognizer setParameter:@"1" forKey:[IFlySpeechConstant RECORDER_INIT]];
        //设置识别域
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        _iFlySpeechRecognizer.delegate = self;
        
        /*
         设置识别引擎的参数
         *
         *  识别的引擎参数(key)取值如下：
         *
         *  | 参数             | 描述                                                  |
         *  |-----------------|-------------------------------------------------------|
         *  | domain          | 应用的领域: 取值为:iat、search、video、poi、music、asr；<br>iat：普通文本听写；<br>search：热词搜索；<br>video：视频音乐搜索；<br>asr：关键词识别;|
         *  | vad_bos         | 前端点检测: 静音超时时间，即用户多长时间不说话则当做超时处理； 单位：ms；<br>engine指定iat识别默认值为5000；<br>其他情况默认值为 4000，范围 0-10000。|
         *  | vad_eos         | 后断点检测: 后端点静音检测时间,即用户停止说话多长时间内即认为不再输入,自动停止录音；单位:ms;<br>sms 识别默认值为 1800;<br>其他默认值为 700，范围 0-10000。|
         *  | sample_rate     | 采样率:目前支持的采样率设置有 16000 和 8000。|
         *  | asr_ptt         | 标点符号设置: 默认为 1，当设置为 0 时，将返回无标点符号文本。|
         *  | result_type     | 返回结果的数据格式: 可设置为json，xml，plain，默认为json。|
         *  | grammarID       | 识别的语法id: 只针对 domain 设置为”asr”的应用。|
         *  | asr_audio_path  | 音频文件名: 设置此参数后，将会自动保存识别的录音文件。<br>路径为Documents/(指定值)。<br>不设置或者设置为nil，则不保存音频。|
         *  | params          | 扩展参数: 对于一些特殊的参数可在此设置，一般用于设置语义。|
         */
        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            
            //设置录制超时时间
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //设置语音结束VAD超时（EOS）
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];//超过3000ms用户停止说话视为结束录音
            //设置语音开始的VAD超时（BOS）
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];//录音开始超过5000ms不说话超时处理
            //设置网络超时时间
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //设置采样率，16K作为推荐选项
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //设置语言
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置口音
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            
            //设置是否在识别结果中显示标点符号
            [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
        
    }else  {
        if (_iflyRecognizerView == nil) {
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        }
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        _iflyRecognizerView.delegate = self;
        
        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
        }
    }
    
    if([[IATConfig sharedInstance].language isEqualToString:@"en_us"]){
        if([IATConfig sharedInstance].isTranslate){
            [self translation:NO];
        }
    }
    else{
        if([IATConfig sharedInstance].isTranslate){
            [self translation:YES];
        }
    }
    
}
//翻译
-(void)translation:(BOOL) langIsZh{
    if ([IATConfig sharedInstance].haveView == NO) {
        [_iFlySpeechRecognizer setParameter:@"1" forKey:[IFlySpeechConstant ASR_SCH]];
        if(langIsZh){
            [_iFlySpeechRecognizer setParameter:@"cn" forKey:@"orilang"];
            [_iFlySpeechRecognizer setParameter:@"en" forKey:@"translang"];
        }else{
            [_iFlySpeechRecognizer setParameter:@"en" forKey:@"orilang"];
            [_iFlySpeechRecognizer setParameter:@"cn" forKey:@"translang"];
        }
        
        [_iFlySpeechRecognizer setParameter:@"translate" forKey:@"addcap"];
        [_iFlySpeechRecognizer setParameter:@"its" forKey:@"trssrc"];
    }
    else{
        [_iflyRecognizerView setParameter:@"1" forKey:[IFlySpeechConstant ASR_SCH]];
        
        if(langIsZh){
            [_iflyRecognizerView setParameter:@"cn" forKey:@"orilang"];
            [_iflyRecognizerView setParameter:@"en" forKey:@"translang"];
        }else{
            [_iflyRecognizerView setParameter:@"en" forKey:@"orilang"];
            [_iflyRecognizerView setParameter:@"cn" forKey:@"translang"];
        }
        
        [_iflyRecognizerView setParameter:@"translate" forKey:@"addcap"];
        
        [_iflyRecognizerView setParameter:@"its" forKey:@"trssrc"];
    }
    
    
}
 
/*
 //自带语音识别
-(void)startRecording{
    if (self.recognitionTask) {
        [self.recognitionTask cancel];
        self.recognitionTask = nil;
    }
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    bool  audioBool = [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
    bool  audioBool1= [audioSession setMode:AVAudioSessionModeMeasurement error:nil];
    bool  audioBool2= [audioSession setActive:true withOptions:AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation error:nil];
    if (audioBool || audioBool1||  audioBool2) {
        NSLog(@"可以使用");
    }else{
        NSLog(@"这里说明有的功能不支持");
    }
    self.recognitionRequest = [[SFSpeechAudioBufferRecognitionRequest alloc]init];
    AVAudioInputNode *inputNode = self.audioEngine.inputNode;
    SFSpeechAudioBufferRecognitionRequest *recognitionRequest;
    self.recognitionRequest.shouldReportPartialResults = true;
    
    　　//开始识别任务
    self.recognitionTask = [self.speechRecognizer recognitionTaskWithRequest:self.recognitionRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) {
        bool isFinal = false;
        if (result) {
            //语音转文本
            [self.textDocumentProxy insertText:[[result bestTranscription] formattedString]];
            isFinal = [result isFinal];
        }
        if (error || isFinal) {
            [self.audioEngine stop];
            [inputNode removeTapOnBus:0];
            self.recognitionRequest = nil;
            self.recognitionTask = nil;
        }
    }];
    AVAudioFormat *recordingFormat = [inputNode outputFormatForBus:0];
    [inputNode installTapOnBus:0 bufferSize:1024 format:recordingFormat block:^(AVAudioPCMBuffer * _Nonnull buffer, AVAudioTime * _Nonnull when) {
        [self.recognitionRequest appendAudioPCMBuffer:buffer];
    }];
    [self.audioEngine prepare];
    bool audioEngineBool = [self.audioEngine startAndReturnError:nil];
    NSLog(@"%d",audioEngineBool);
    
}
 */

#pragma  mark 键盘输入特有代理
- (void)textWillChange:(id<UITextInput>)textInput {
    // The app is about to change the document's contents. Perform any preparation here.
}
- (void)textDidChange:(id<UITextInput>)textInput {
    // The app has just changed the document's contents, the document context has been updated.
    UIColor *textColor = nil;
    if (self.textDocumentProxy.keyboardAppearance == UIKeyboardAppearanceDark) {
        textColor = [UIColor whiteColor];
    } else {
        textColor = [UIColor blackColor];
    }
    [self.nextKeyboardButton setTitleColor:textColor forState:UIControlStateNormal];
}

#pragma mark - IFlySpeechRecognizerDelegate 
/*!
 *  识别结果回调
 *
 *  在识别过程中可能会多次回调此函数，你最好不要在此回调函数中进行界面的更改等操作，只需要将回调的结果保存起来。<br>
 *  使用results的示例如下：
 *  @param results  -[out] 识别结果，NSArray的第一个元素为NSDictionary，NSDictionary的key为识别结果，sc为识别结果的置信度。
 *  @param isLast   -[out] 是否最后一个结果
 */
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    NSLog(@"result===%@",resultString);
    
    NSString * resultFromJson =  nil;
    
    if([IATConfig sharedInstance].isTranslate){
        
        NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData: //结果类型必须是utf8，否则会发生未知错误。
                                    [resultString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        if(resultDic != nil){
            NSDictionary *trans_result = [resultDic objectForKey:@"trans_result"];
            
            if([[IATConfig sharedInstance].language isEqualToString:@"en_us"]){
                NSString *dst = [trans_result objectForKey:@"dst"];
                NSLog(@"dst=%@",dst);
                resultFromJson = [NSString stringWithFormat:@"%@\ndst:%@",resultString,dst];
            }
            else{
                NSString *src = [trans_result objectForKey:@"src"];
                NSLog(@"src=%@",src);
                resultFromJson = [NSString stringWithFormat:@"%@\nsrc:%@",resultString,src];
            }
        }
    }
    else{
        resultFromJson = [ISRDataHelper stringFromJson:resultString];
    }
    
    NSLog(@"结果===%@",resultFromJson);
    
}
 

/*!
 *  音量变化回调<br>
 *  在录音过程中，回调音频的音量。
 *
 *  @param volume -[out] 音量，范围从0-30
 */
- (void) onVolumeChanged: (int)volume
{
    if (self.isCanceled) {
        [_popUpView removeFromSuperview];
        return;
    }
    
    NSString * vol = [NSString stringWithFormat:@"%@：%d", NSLocalizedString(@"T_RecVol", nil),volume];
    [_popUpView showText: vol];
}



/*!
 *  开始录音回调<br>
 *  当调用了`startListening`函数之后，如果没有发生错误则会回调此函数。<br>
 *  如果发生错误则回调onCompleted:函数
 */
- (void) onBeginOfSpeech
{
    NSLog(@"onBeginOfSpeech");
    self.isBeginOfSpeech = YES;
    
    [_popUpView showText: NSLocalizedString(@"T_RecNow", nil)];
}

/*!
 *  停止录音回调<br>
 *  当调用了`stopListening`函数或者引擎内部自动检测到断点，如果没有发生错误则回调此函数。<br>
 *  如果发生错误则回调onCompleted:函数
 */
- (void) onEndOfSpeech{
    NSLog(@"onEndOfSpeech");
    [_popUpView showText: NSLocalizedString(@"T_RecStop", nil)];
}

/*!
 *  取消识别回调<br>
 *  当调用了`cancel`函数之后，会回调此函数，在调用了cancel函数和回调onCompleted之前会有一个<br>
 *  短暂时间，您可以在此函数中实现对这段时间的界面显示。
 */
- (void) onCancel
{
    NSLog(@"Recognition is cancelled");
}


#pragma  mark  IFlyRecognizerViewDelegate
/*!
 *  识别结果回调
 *
 *  在进行语音识别过程中的任何时刻都有可能回调此函数，你可以根据errorCode进行相应的处理，当errorCode没有错误时，表示此次会话正常结束；否则，表示此次会话有错误发生。特别的当调用`cancel`函数时，引擎不会自动结束，需要等到回调此函数，才表示此次会话结束。在没有回调此函数之前如果重新调用了`startListenging`函数则会报错误。
 *
 *  @param error 错误描述
 */
- (void) onCompleted:(IFlySpeechError *) error
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO ) {
        
        NSString *text ;
        
        if (self.isCanceled) {
            text = NSLocalizedString(@"T_ISR_Cancel", nil);
            
        } else if (error.errorCode == 0 ) {
           text = NSLocalizedString(@"T_ISR_NoRlt", nil);
        }else {
            text = [NSString stringWithFormat:@"Error：%d %@", error.errorCode,error.errorDesc];
            
        }
        
         [_popUpView showText: @"Recording faild"];//录音失败
        
    }else {
        [_popUpView showText: NSLocalizedString(@"T_ISR_Succ", nil)];
        NSLog(@"errorCode:%d",[error errorCode]);
    }
   
}



/*!
 *  回调返回识别结果w
 *
 *  @param resultArray 识别结果，NSArray的第一个元素为NSDictionary，NSDictionary的key为识别结果，sc为识别结果的置信度
 *  @param isLast      -[out] 是否最后一个结果
 */
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    NSString * resultFromJson =  nil;
    
    if([IATConfig sharedInstance].isTranslate){
        
        NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData://结果类型必须是utf8，否则会发生未知错误。
                                    [resultString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        if(resultDic != nil){
            NSDictionary *trans_result = [resultDic objectForKey:@"trans_result"];
            
            if([[IATConfig sharedInstance].language isEqualToString:@"en_us"]){
                NSString *dst = [trans_result objectForKey:@"dst"];
                NSLog(@"dst=%@",dst);
                resultFromJson = [NSString stringWithFormat:@"%@\ndst:%@",resultString,dst];
            }
            else{
                NSString *src = [trans_result objectForKey:@"src"];
                NSLog(@"src=%@",src);
                resultFromJson = [NSString stringWithFormat:@"%@\nsrc:%@",resultString,src];
            }
        }
    }
    else{
        resultFromJson = [NSString stringWithFormat:@"%@",resultString];//;[ISRDataHelper stringFromJson:resultString];
    }
    NSLog(@"最终===%@",resultFromJson);
    
}


@end

